package com.example.controller;

import com.example.dto.UserDto;
import com.example.entity.User;
import com.example.service.impl.UserServiceimpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/changePass")
public class ChangePasswordServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();

        User user = (User) session.getAttribute("user");
        String username = user.getUsername();
        String oldPass = req.getParameter("OldPass");
        String newPass = req.getParameter("NewPass");

        UserServiceimpl userServiceimpl = new UserServiceimpl();
        UserDto userDto = userServiceimpl.changePassword(username, oldPass, newPass);


        if(userDto.getMsg().equals("密码修改成功")){
            req.getSession().setAttribute("user", userDto.getUser());
            req.setAttribute("Msg", userDto.getMsg());
            req.getRequestDispatcher("/changePass.jsp").forward(req, resp);
        }else{
            req.setAttribute("Msg", userDto.getMsg());
            req.getRequestDispatcher("/changePass.jsp").forward(req, resp);
        }
    }
}
